import React, { useState } from 'react';
import { Modal, Form, Input, Select, Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Article, Column } from '@/types/content';
import { ARTICLE_STATUS_OPTIONS } from '@/utils/mappings';
import MDEditor from '@/components/MDEditor';
import { contentService } from '@/services/contentService';
import { websiteService } from '@/services/websiteService';

const { Option } = Select;

interface ArticleEditorProps {
  visible: boolean;
  editingArticle: Article | null;
  columns: Column[];
  onCancel: () => void;
  onSuccess: () => void;
}

const ArticleEditor: React.FC<ArticleEditorProps> = ({
  visible,
  editingArticle,
  columns,
  onCancel,
  onSuccess
}) => {
  const [form] = Form.useForm();
  const [coverUrl, setCoverUrl] = useState<string>('');
  const [uploading, setUploading] = useState(false);
  const [mdContent, setMdContent] = useState('');

  // 当编辑状态改变时，重置表单
  React.useEffect(() => {
    if (visible) {
      if (editingArticle) {
        form.setFieldsValue({
          ...editingArticle,
          column_id: editingArticle.column.id,
          is_published: editingArticle.is_published,
        });
        setMdContent(editingArticle.content);
        setCoverUrl(editingArticle.cover || '');
      } else {
        form.resetFields();
        setMdContent('');
        setCoverUrl('');
      }
    }
  }, [visible, editingArticle, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      
      const formData = new FormData();
      formData.append('title', values.title);
      formData.append('summary', values.summary || '');
      formData.append('content', mdContent);
      formData.append('column_id', values.column_id);
      formData.append('is_published', values.is_published);
      if (coverUrl) {
        formData.append('cover', coverUrl);
      }
      
      if (editingArticle) {
        await contentService.updateArticle(editingArticle.id, formData);
        message.success('修改成功');
      } else {
        await contentService.createArticle(formData);
        message.success('新建成功');
      }
      onSuccess();
    } catch (error) {
      console.error('保存文章失败:', error);
      message.error('保存失败');
    }
  };



  return (
    <Modal
      title={editingArticle ? '编辑文章' : '新建文章'}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={700}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}> 
          <Input maxLength={50} />
        </Form.Item>
        <Form.Item name="summary" label="摘要">
          <Input.TextArea maxLength={200} rows={2} />
        </Form.Item>
        <Form.Item name="column_id" label="栏目" rules={[{ required: true, message: '请选择栏目' }]}> 
          <Select placeholder="请选择栏目">
            {columns.map(col => <Option value={col.id} key={col.id}>{col.name}</Option>)}
          </Select>
        </Form.Item>
        <Form.Item name="is_published" label="发布状态" initialValue={true}>
          <Select>
            {ARTICLE_STATUS_OPTIONS.map(opt => <Option value={opt.value} key={String(opt.value)}>{opt.label}</Option>)}
          </Select>
        </Form.Item>
        <Form.Item label="封面图片">
          <Upload
            beforeUpload={async (file) => {
              console.log('beforeUpload called with file:', file);
              // 直接在这里处理文件上传
              setUploading(true);
              try {
                const uploadedUrl = await websiteService.uploadImage(file);
                console.log('uploadedUrl:', uploadedUrl);
                setCoverUrl(uploadedUrl);
                message.success('封面图片上传成功');
              } catch (error) {
                message.error('封面图片上传失败');
              } finally {
                setUploading(false);
              }
              // 返回 false 阻止默认上传行为
              return false;
            }}
            maxCount={1}
            onChange={(info) => {
              console.log('onChange called with info:', info);
            }}
            showUploadList={false}
            accept="image/*"
          >
            <Button icon={<UploadOutlined />} loading={uploading}>
              {uploading ? '上传中...' : '选择图片'}
            </Button>
          </Upload>
          {(coverUrl || (editingArticle && editingArticle.cover)) && (
            <div style={{ marginTop: 8 }}>
              <img 
                src={coverUrl || editingArticle?.cover} 
                alt="cover" 
                style={{ width: 100, height: 60, objectFit: 'cover', borderRadius: 4 }} 
              />
              {coverUrl && (
                <div style={{ marginTop: 4, fontSize: '12px', color: '#52c41a' }}>
                  ✓ 封面图片已上传
                </div>
              )}
            </div>
          )}
        </Form.Item>
        <Form.Item label="正文内容" required>
          <MDEditor value={mdContent} onChange={v => setMdContent(v || '')} height={300} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ArticleEditor; 